'use strict';

const Service = require('egg').Service;

class RoleService extends Service {

  // 新增角色
  async createRole(payload) {
    const { app } = this;
    return await app.model.Role.create(payload);
  }

  // 获取列表
  async getRoleList(pageNum, pageSize) {
    const { app } = this;
    try {
      const offset = (pageNum - 1) * pageSize;
      const { count, rows } = await app.model.Role.findAndCountAll({
        include: [
          {
            model: this.app.model.User,
            as: 'user',
            attributes: [ 'user_name' ],
            through: { attributes: [] }, // 排除中间表

          },
        ],
        order: [
          [ 'createdAt', 'desc' ],
          // [ 'id', 'desc' ],
        ],
        offset,
        limit: pageSize * 1,
      });
      return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // 根据id获取信息
  async getInfo(id) {
    return await this.app.model.Role.findByPk(id);
  }

  // 删除角色
  async destroyRole(payload) {
    const { app } = this;
    const allRoles = await app.model.Role.findAll({ where: { id: payload.ids } });
    if (!allRoles.every(e => e.is_default !== 1)) return { err: 1 };
    return await app.model.Role.destroy({ where: { id: payload.ids }, force: true });
  }

  // 修改角色
  async updateRole(id, payload) {
    const { app } = this;
    return await app.model.Role.update(payload, { where: { id } });
  }
  // 设置默认角色
  async setDefaultRole(id) {
    const { app } = this;
    const transaction = await app.model.transaction();
    await app.model.Role.update({ is_default: 0 }, { where: { is_default: 1 }, transaction });
    const res = await app.model.Role.update({ is_default: 1 }, { where: { id }, transaction });
    if (res && res[0] === 1) {
      await transaction.commit();
      return true;
    }
    await transaction.rollback();
    return false;
  }

}

module.exports = RoleService;
